<?php
namespace app\api\controller;

use app\api\controller\Authbase;
use app\api\model\ArticleModel;
use think\Controller;

/**
 * 美文接口
 */
class Article extends Authbase
{
    /**
     * 美文首页 看美图
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index() {
        $page = input('page/d', 1);
        $data = ArticleModel::getList($page);
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '没有更新的数据了']);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 美文详情
     *
     */
    public function view() {
        $article_id = input('article_id/d', '');
        if (empty($article_id)) {
            return json(['code' => 0, 'error' => '请传递参数article_id']);
        }
        $article = ArticleModel::detail($article_id);
        return json(['code' => 1, 'msg' => 'success', 'data' => $article]);
    }

    /**
     * 推介list
     */
    public function recommend() {
        $page_index = input('page_index/d', 1);
        $page = input('page/d', 1);
        $article = ArticleModel::recommend($page, $page_index, $this->useMode);
        //var_dump($article);die;
        if (empty($article)) {
            return json(['code' => 0, 'msg' => '没有更新的数据了']);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => $article]);
    }

    /**
     * 点击事件
     *
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function click() {
        $article_id = input('id/d', '');
        if(empty($article_id)) {
            return json(['code' => 0, 'error' => '请传递id']);
        }
        if (!$res = ArticleModel::click($article_id, $this->useMode)) {
            return json(['code' => 0, 'error' => ArticleModel::$error_msg]);
        }
        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 分享事件
     * @return \think\response\Json
     */
    public function share() {
        $article_id = input('id/d', '');
        if(empty($article_id)) {
            return json(['code' => 0, 'error' => '请传递id']);
        }
        $articleM = new ArticleModel();
        if (!$articleM->share($article_id)) {
            return json(['code' => 0, 'error' => $articleM->getError()]);
        }
        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 分享过后的推介
     * 算法：过滤掉已读，随机五条
     * 如果
     */
    public function after_share() {
        $article = ArticleModel::afterShare($this->useMode);
        if (!$article) {
            return json(['code' => 0, 'error' => ArticleModel::$error_msg]);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => $article]);
    }
}